/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kylingroup.JavaFX.Task;

/**
 *
 * @author kylin
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {
    Task copyWorker;
    
    int MAX=100;
        ProgressBar bar;
        double count;
        long size =0;
        int length = 0;
        long cLength = 0;
    
    public static void main(String[] args) {
        Application.launch(args);
    }
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Background Processes");
        Group root = new Group();
        Scene scene = new Scene(root, 330, 120, Color.WHITE);

        BorderPane mainPane = new BorderPane();
        root.getChildren().add(mainPane);

        final Label label = new Label("Files Transfer:");
        final ProgressIndicator progressIndicator = new ProgressIndicator(0);

        final HBox hb = new HBox();
        hb.setSpacing(5);
        hb.setAlignment(Pos.CENTER);
        hb.getChildren().addAll(label, progressIndicator);
        mainPane.setTop(hb);

        final Button startButton = new Button("Start");
        final Button cancelButton = new Button("Cancel");
        final HBox hb2 = new HBox();
        hb2.setSpacing(5);
        hb2.setAlignment(Pos.CENTER);
        hb2.getChildren().addAll(startButton, cancelButton);
        mainPane.setBottom(hb2);

        startButton.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent event) {
                startButton.setDisable(true);
                progressIndicator.setProgress(0);
                cancelButton.setDisable(false);
                copyWorker = createWorker();

                progressIndicator.progressProperty().unbind();
                progressIndicator.progressProperty().bind(copyWorker.progressProperty());
               
                copyWorker.messageProperty().addListener(new ChangeListener<String>() {
                    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                        System.out.println(newValue);
                    }
                });

                new Thread(copyWorker).start();
            }
        });
        cancelButton.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {
                startButton.setDisable(false);
                cancelButton.setDisable(true);
                copyWorker.cancel(true);
                progressIndicator.progressProperty().unbind();
                progressIndicator.setProgress(0);
                System.out.println("cancelled.");
            }
        });
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public Task createWorker() {
        
        return new Task() {
            @Override
            protected Object call() throws Exception {
//                for (int i = 0; i < 10; i++) {
//                    Thread.sleep(2000);
//                    updateMessage("2000 milliseconds");
//                    updateProgress(i + 1, 10);
//                }
                File file = new File("/home/kylin/Shared/KGFileuploader1.0.zip");
            size = file.length();
            int bufferedsize=(int) (size / (Math.random() * 50 + MAX - 50));
            byte[] bts = new byte[bufferedsize];
            System.out.println("buffersize: "+bufferedsize);
            length = 0;
            cLength = 0;
            try{
		InputStream stream = new FileInputStream(file);
		OutputStream os = new FileOutputStream(new File("/home/kylin/Shared/8422.zip"));
		while((length = stream.read(bts)) > 0){
                    os.write(bts, 0, length);
                    cLength += length;
                    
                    //bar.setProgress((int) (cLength * MAX / size));
                    
//                    try {
//                        Thread.sleep(100);
//                    } catch (InterruptedException ex) {
//                        Logger.getLogger(TestJavaFXTask.class.getName()).log(Level.SEVERE, null, ex);
//                    }
                    Thread.sleep(2000);
                    updateMessage("2000 milliseconds");
                    updateProgress(cLength * MAX ,size);
		}
                os.flush();
		os.close();
		stream.close();
                System.out.println("finished!");
                //myTask.cancel();
            }
            catch(Exception e){
                e.printStackTrace();
            }
                return true;
            }
        };
    }
}